package com.fare.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;

public class ExcelUtil {

	/**
	 * 将HBase中的数据导出到excel中
	 * 
	 * @param scan
	 * @param path
	 * @param fileName
	 * @throws IOException
	 * @throws WriteException
	 * @throws RowsExceededException
	 */
	public static int exportHBaseDataToExcel(WritableSheet sheet,
			ResultScanner scan, int row) throws IOException,
			WriteException, RowsExceededException {

		Map<String, Integer> planeInfoTitleMap = new HashMap<String, Integer>();
		Map<String, String> planeInfoRecordMap = null;
		int col = 1;
		sheet.addCell(new Label(0, 0, "ROWKEY"));
		for (Result res : scan) {
			planeInfoRecordMap = new HashMap<String, String>();
			for (KeyValue kv : res.raw()) {
				if (planeInfoTitleMap.get(new String(kv.getQualifier())) == null) {
					sheet.addCell(new Label(col, 0, new String(kv
							.getQualifier())));
					planeInfoTitleMap.put(new String(kv.getQualifier()), col++);
				}
				planeInfoRecordMap.put(new String(kv.getQualifier()),
						new String(kv.getValue()));
			}
			for (Entry<String, Integer> e : planeInfoTitleMap.entrySet()) {
				sheet.addCell(new Label(e.getValue(), row, planeInfoRecordMap
						.get(e.getKey())));
			}
			sheet.addCell(new Label(0, row, new String(res.getRow())));
			row++;
		}
		return row++;
	}

	/**
	 * 创建xls文件
	 * 
	 * @param filePath
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	private static File createFile(String filePath, String fileName)
			throws IOException {
		String excelpath = filePath ;
		System.out.println("输出路径：" + excelpath);
		// 创建文件
		File path = new File(excelpath);
		if (path.exists()) {
			path.delete();
			path.createNewFile();
		} else {
			path.mkdirs();
		}
		File file = new File(filePath+File.separator+fileName);
		file.createNewFile();
		return file;

	}
}
